import { z } from 'zod';
import { router } from '../trpc';
import { adminProcedure, superAdminProcedure } from '../middleware';
import { AdminService } from '../../services/adminService';
import { createSuccessResponse, createErrorResponse } from '../../utils/response';

// 输入验证schemas
const createSubAdminSchema = z.object({
  email: z.string().email('Invalid email format'),
  username: z.string().min(3, 'Username must be at least 3 characters'),
  password: z.string().min(6, 'Password must be at least 6 characters'),
});

const createCustomerSchema = z.object({
  email: z.string().email('Invalid email format'),
  username: z.string().min(3, 'Username must be at least 3 characters'),
  password: z.string().min(6, 'Password must be at least 6 characters'),
});

const updateUserSchema = z.object({
  userId: z.number().int().positive('Invalid user ID'),
  email: z.string().email('Invalid email format').optional(),
  username: z.string().min(3, 'Username must be at least 3 characters').optional(),
  isActive: z.boolean().optional(),
  role: z.enum(['ADMIN', 'SUB_ADMIN', 'USER']).optional(),
});

const deleteUserSchema = z.object({
  userId: z.number().int().positive('Invalid user ID'),
});

const getUsersSchema = z.object({
  page: z.number().int().positive().default(1),
  limit: z.number().int().positive().max(100).default(20),
});

const updateQuickAmountsSchema = z.object({
  amounts: z.array(z.number().positive('Amount must be positive')).min(1, 'At least one amount is required'),
});


const updatePurchasePriceInfoSchema = z.object({
  priceInfo: z.string().trim().min(1, 'Price info cannot be empty').max(50, 'Price info cannot exceed 50 characters'),
});

const productConfigSchema = z.object({
  id: z.number().int().positive().optional(),
  coinAmount: z.number().positive('Coin amount must be positive'),
  productId: z.number().int().positive('Product ID must be positive'),
  isActive: z.boolean(),
  description: z.string().optional(),
  sortOrder: z.number().int().min(0, 'Sort order must be non-negative'),
});

const updateProductConfigsSchema = z.object({
  configs: z.array(productConfigSchema).min(1, 'At least one product config is required'),
});

export const adminRouter = router({
  /**
   * 创建子管理员 (仅超级管理员)
   */
  createSubAdmin: superAdminProcedure
    .input(createSubAdminSchema)
    .mutation(async ({ input, ctx }) => {
      try {
        const subAdmin = await AdminService.createSubAdmin(ctx.user.userId, input);
        return createSuccessResponse(subAdmin, 'Sub-admin created successfully');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : 'Failed to create sub-admin',
          'ADMIN_ERROR'
        );
      }
    }),

  /**
   * 创建普通用户（客户）
   */
  createCustomer: adminProcedure
    .input(createCustomerSchema)
    .mutation(async ({ input, ctx }) => {
      try {
        const customer = await AdminService.createCustomer(ctx.user.userId, input);
        return createSuccessResponse(customer, 'Customer created successfully');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : 'Failed to create customer',
          'ADMIN_ERROR'
        );
      }
    }),

  /**
   * 获取所有用户列表
   */
  getAllUsers: adminProcedure
    .input(getUsersSchema)
    .query(async ({ input, ctx }) => {
      try {
        const result = await AdminService.getAllUsers(
          ctx.user.userId,
          input.page,
          input.limit
        );
        return createSuccessResponse(result, 'Users retrieved successfully');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : 'Failed to get users',
          'ADMIN_ERROR'
        );
      }
    }),

  /**
   * 获取子管理员列表 (仅超级管理员)
   */
  getSubAdmins: superAdminProcedure
    .query(async ({ ctx }) => {
      try {
        const subAdmins = await AdminService.getSubAdmins(ctx.user.userId);
        return createSuccessResponse(subAdmins, 'Sub-admins retrieved successfully');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : 'Failed to get sub-admins',
          'ADMIN_ERROR'
        );
      }
    }),

  /**
   * 更新用户信息
   */
  updateUser: adminProcedure
    .input(updateUserSchema)
    .mutation(async ({ input, ctx }) => {
      try {
        const { userId, ...updateData } = input;
        const updatedUser = await AdminService.updateUser(
          ctx.user.userId,
          userId,
          updateData
        );
        return createSuccessResponse(updatedUser, 'User updated successfully');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : 'Failed to update user',
          'ADMIN_ERROR'
        );
      }
    }),

  /**
   * 删除用户
   */
  deleteUser: adminProcedure
    .input(deleteUserSchema)
    .mutation(async ({ input, ctx }) => {
      try {
        await AdminService.deleteUser(ctx.user.userId, input.userId);
        return createSuccessResponse(null, 'User deleted successfully');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : 'Failed to delete user',
          'ADMIN_ERROR'
        );
      }
    }),

  /**
   * 获取系统统计信息
   */
  getSystemStats: adminProcedure
    .query(async ({ ctx }) => {
      try {
        const stats = await AdminService.getSystemStats(ctx.user.userId);
        return createSuccessResponse(stats, 'System stats retrieved successfully');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : 'Failed to get system stats',
          'ADMIN_ERROR'
        );
      }
    }),

  /**
   * 检查管理员权限
   */
  checkAdminPermission: adminProcedure
    .query(async ({ ctx }) => {
      try {
        const isAdmin = await AdminService.checkAdminPermission(ctx.user.userId);
        const isSuperAdmin = await AdminService.checkSuperAdminPermission(ctx.user.userId);
        
        return createSuccessResponse(
          {
            isAdmin,
            isSuperAdmin,
            role: ctx.user.role,
          },
          'Permission check completed'
        );
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : 'Failed to check permissions',
          'ADMIN_ERROR'
        );
      }
    }),

  /**
   * 获取快捷金额配置
   */
  getQuickAmounts: adminProcedure
    .query(async ({ ctx }) => {
      try {
        const quickAmounts = await AdminService.getQuickAmounts(ctx.user.userId);
        return createSuccessResponse(quickAmounts, 'Quick amounts retrieved successfully');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : 'Failed to get quick amounts',
          'ADMIN_ERROR'
        );
      }
    }),

  /**
   * 更新快捷金额配置
   */
  updateQuickAmounts: adminProcedure
    .input(updateQuickAmountsSchema)
    .mutation(async ({ input, ctx }) => {
      try {
        const updatedAmounts = await AdminService.updateQuickAmounts(ctx.user.userId, input.amounts);
        return createSuccessResponse(updatedAmounts, 'Quick amounts updated successfully');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : 'Failed to update quick amounts',
          'ADMIN_ERROR'
        );
      }
    }),



  /**
   * 获取购买价格信息配置
   */
  getPurchasePriceInfo: adminProcedure
    .query(async ({ ctx }) => {
      try {
        const result = await AdminService.getPurchasePriceInfo(ctx.user.userId);
        return createSuccessResponse(result, '获取购买价格信息成功');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : 'Failed to get purchase price info',
          'ADMIN_ERROR'
        );
      }
    }),

  /**
   * 更新购买价格信息配置
   */
  updatePurchasePriceInfo: adminProcedure
    .input(updatePurchasePriceInfoSchema)
    .mutation(async ({ input, ctx }) => {
      try {
        const updatedPriceInfo = await AdminService.updatePurchasePriceInfo(ctx.user.userId, input.priceInfo);
        return createSuccessResponse(updatedPriceInfo, '购买价格信息更新成功');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : 'Failed to update purchase price info',
          'ADMIN_ERROR'
        );
      }
    }),

  /**
   * 获取产品配置列表
   */
  getProductConfigs: adminProcedure
    .query(async ({ ctx }) => {
      try {
        const configs = await AdminService.getProductConfigs(ctx.user.userId);
        return createSuccessResponse(configs, 'Product configs retrieved successfully');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : 'Failed to get product configs',
          'ADMIN_ERROR'
        );
      }
    }),

  /**
   * 更新产品配置
   */
  updateProductConfigs: adminProcedure
    .input(updateProductConfigsSchema)
    .mutation(async ({ input, ctx }) => {
      try {
        const updatedConfigs = await AdminService.updateProductConfigs(ctx.user.userId, input.configs);
        return createSuccessResponse(updatedConfigs, 'Product configs updated successfully');
      } catch (error) {
        return createErrorResponse(
          error instanceof Error ? error.message : 'Failed to update product configs',
          'ADMIN_ERROR'
        );
      }
    }),
});
